<template>
	<view class="createAiPersonStepTwo bg-white">
		<view class="flex">
			<view class="mb-10" style="display: inline-block;">
				<text style="font-size: 30rpx;">自我介绍</text>
			</view>
		</view>
		<view>
			<u--textarea 
			@input="aiTextInputChange"
			v-model="aiText" 
			placeholder="请输入智能体自我介绍的内容"
			height="200"
			maxlength="300"
			count
			></u--textarea>
		</view>
		<view class="mt-10">
			<u--text 
			text="示例:" ></u--text>
			<u-read-more showHeight="60" toggle closeText="展开示例">
					<rich-text :nodes="sampleText"></rich-text>
				</u-read-more>
		</view>
		<view class="mt-20">
			<u-line></u-line>
			<view class="mt-20">
				<u--text
				text="请选择配音"
				color="#909399"></u--text>
			</view>
			<u-tabs :list="[{name:'男声'}]" @click="click"></u-tabs>
			<view class="voiceList flex justify-between mt-20 ml-20">
				<u-tag @click="voiceTagClick(voice.voiceType)" 
				v-for="(voice, index) in maleVoiceList" :key="index" :text="voice.title" 
				:type="selectedVoice == voice.voiceType ? 'primary' : 'info'"
				plain shape="circle" size="large"></u-tag>
			</view>
			<u-tabs :list="[{name:'女声'}]" @click="click"></u-tabs>
			<view class="voiceList flex justify-between mt-20 ml-20">
				<u-tag @click="voiceTagClick(voice.voiceType)" 
				v-for="(voice, index) in femaleVoiceList" :key="index" :text="voice.title" 
				:type="selectedVoice == voice.voiceType ? 'primary' : 'info'"
				plain shape="circle" size="large"></u-tag>
			</view>
			<u-tabs :list="[{name:'试听'}]" @click="click"></u-tabs>
			<view class="flex align-center mt-20">
				<u-loading-icon 
				v-if="voiceLoading"
				size="36"></u-loading-icon>
				<u-icon
				@click="playBtnClick"
				  size="40"
				  color="#2979ff"
				  :name="voicePlayStaus == 'playing' ? 'pause-circle' : 'play-circle'"
				  v-else
				></u-icon>
				<view class="ml-10" style="width: 700rpx;">
					<view class="flex justify-between">
						<view>
							<u--text 
							:text="'00:' + (voiceCurrentTime ? (voiceCurrentTime < 9.49 ? '0' : '') + voiceCurrentTime.toFixed(0) : '00')"
							color="#909399"></u--text>
						</view>
						<view>
							<u--text 
							:text="'00:' + (voiceLength ? voiceLength.toFixed(0) : '00')"
							color="#909399"></u--text>
						</view>
					</view>
					<u-line-progress :percentage="voiceBarPercentage" :showText="false" activeColor="#2979ff"></u-line-progress>
				</view>
			</view>
			<view v-show="voiceLoading" class="mt-10">
				<u--text
				size="24rpx"
				text="音频生成中, 请稍后..."
				color="#909399"></u--text>
			</view>
		</view>
		<view class="createAiPersonStepTwo-btnBlank"></view>
		<view class="createAiPersonStepTwo-btnList flex mt-20">
			<view class="createAiPersonStepTwo-btnList-btn">
				<u-button @click="confirmBtnClick" :loading="submitLoading" :text="confirmText" type="primary" size="large"></u-button>
			</view>
		</view>
		<u-toast ref="toast"></u-toast>
	</view>
</template>

<script>
	import api from "@/api/api";
	export default {
		data() {
			return {
				imgUrl: null,
				aiText: "",
				sampleText: "大家好，我是大壮，XXXX公司的经理。很高兴在这里与您相识！我们霄客技术是一家专注于数字营销的高新技术企业，致力于为中小企业提供智能化的营销解决方案，助力企业高效增长。我们运用AI大模型技术，能够自动生成高质量内容，大幅提升市场团队的生产效率，并通过媒体矩阵快速发布，优化用户体验。依托1.9亿+企业知识图谱和3.6亿+消费者画像资源，我们实现全域化、数字化、智能化的营销服务，帮助企业构建高效的获客矩阵，搭建自有流量池。我们的霄客云产品，为企业服务商、制造供应商、消费品牌商、商品零售商四大客群提供一站式数智化营销应用解决方案，精准解决获客难、转化难、成交难等痛点，驱动业绩持续增长。如果您在数字营销方面有任何需求或疑问，欢迎随时联系我。霄客技术，让营销更智能，让增长更简单  。期待与您合作，共创美好未来！",
				selectedVoice: null,
				maleVoiceList: [{
					voiceType: "longcheng",
					title: "男声1"
				},{
					voiceType: "longshu",
					title: "男声2"
				},{
					voiceType: "longshuo",
					title: "男声3"
				}],
				femaleVoiceList:[{
					voiceType: "longwan",
					title: "女声1"
				},{
					voiceType: "longxiaoxia",
					title: "女声2"
				},{
					voiceType: "longmiao",
					title: "女声3"
				}],
				voiceLoading: false,
				voiceUrl: null,
				voicePlayStaus: "init",
				innerAudioContext: null,
				voiceLength: 0,
				voiceCurrentTime: 0,
				voiceBarPercentage: 0,
				submitLoading: false,
				confirmText: "",
				aiVideoCount: 0,
				cardInfo: null,
				cropFaceTaskId: null,
				aiFigureId: null
			};
		},
		components: {
		},
		props: {
		},
		computed: {
		},
		onReady() {
		},
		async onLoad(option) {
			this.imgUrl = option && option.imgUrl ? option.imgUrl : null;
			this.cropFaceTaskId = option && option.cropFaceTaskId ? option.cropFaceTaskId : null;
			this.aiFigureId = option && option.aiFigureId ? option.aiFigureId : null;
			let res = await this.depot.get(api.aiCard("cardInfo/findCardInfo"));
			this.cardInfo = res && res.data && res.data.data ? res.data.data : null;
			if (this.cardInfo) {
				this.confirmText = "确定"
			} else {
				this.confirmText = "下一步"
			}
		},
		mounted() {
		},
		onShow() {
		},
		methods: {
			voiceTagClick(voiceType) {
				this.selectedVoice = voiceType;
				this.resetVoicePlay()
			},
			aiTextInputChange() {
				this.resetVoicePlay()
			},
			async playBtnClick() {
				let vue = this;
				if (this.voicePlayStaus == "playing") {
					this.voicePlayStaus = "pause";
					if (this.innerAudioContext) {
						this.innerAudioContext.pause()
					}
					return;
				} else if (this.voicePlayStaus == "pause" || this.voicePlayStaus == "stop") {
					this.voicePlayStaus = "playing"
					if (this.innerAudioContext) {
						this.innerAudioContext.play()
					}
					return;
				}
				if (this.aiText) {
					if (this.selectedVoice) {
						try {
							this.voiceLoading = true;
							let createVoiceRes = await this.depot.post(api.aiCard("aiVideo/createVoice"),{
								voiceType: this.selectedVoice,
								text: this.aiText
							})
							if (createVoiceRes && createVoiceRes.data && createVoiceRes.data.data) {
								let createVoiceTaskId = createVoiceRes.data.data;
								let findTaskStatusInterval = setInterval(async () => {
									let findTaskStatusRes = await this.depot.get(api.aiCard("createVoiceLog/findOne?id=" + createVoiceTaskId))
									.catch(() => {
										clearInterval(findTaskStatusInterval)
									})
									if (findTaskStatusRes && findTaskStatusRes.data && findTaskStatusRes.data.data) {
										let createVoiceTask = findTaskStatusRes.data.data;
										if (createVoiceTask.createStatus === "DONE") {
											vue.voiceUrl = createVoiceTask.voiceUrl;
											vue.playVoice();
											vue.voiceLoading = false;
											clearInterval(findTaskStatusInterval)
										}
										if (createVoiceTask.status === "FAIL") {
											vue.voiceLoading = false;
											clearInterval(findTaskStatusInterval)
											this.$refs.toast.show({
												type: "error",
												title: "提示",
												message: "AI合成声音失败，请稍后重试!"
											});
										}
									}
								}, 1000, createVoiceTaskId)
								
								// 30秒后关闭，防止内存溢出
								setTimeout(() => {
									if (findTaskStatusInterval) {
										clearInterval(findTaskStatusInterval)
										vue.voiceLoading = false;
									}
								}, 60000)
							} else {
								throw new Error("调用合成音频接口失败");
							}
						} catch (e) {
							this.$refs.toast.show({
								type: "error",
								title: "提示",
								message: "AI合成声音失败，请稍后重试!"
							});
							this.voiceLoading = false;
						}
					} else {
						this.$refs.toast.show({
							type: "error",
							title: "提示",
							message: "请选择声音"
						});
					}
				} else {
					this.$refs.toast.show({
						type: "error",
						title: "提示",
						message: "请输入智能体自我介绍的内容"
					});
					return;
				}
			},
			playVoice() {
				let vue = this;
				if (this.voiceUrl) {
					this.innerAudioContext = this.innerAudioContext ? this.innerAudioContext : uni.createInnerAudioContext();
					this.innerAudioContext.src = this.voiceUrl;
					this.innerAudioContext.play()
					this.voicePlayStaus = "playing";
					this.innerAudioContext.onEnded(() => {
						vue.voicePlayStaus = "stop";
					});
					this.innerAudioContext.onCanplay(() => {
						vue.voiceLength = vue.innerAudioContext.duration;
					});
					let voicePlayInterval = setInterval(() => {
						vue.voiceCurrentTime = vue.innerAudioContext.currentTime;
						vue.voiceBarPercentage = vue.voiceCurrentTime * 100 / vue.voiceLength;
						if (vue.voiceCurrentTime >= vue.voiceLength) {
							vue.voiceBarPercentage = 0;
							clearInterval(voicePlayInterval)
						}
					}, 100)
				}
			},
			resetVoicePlay() {
				this.voicePlayStaus = "init";
				this.voiceLoading = false;
				if (this.innerAudioContext) {
					this.innerAudioContext.seek(0)
					this.innerAudioContext.stop();
				}
			},
			async confirmBtnClick() {
				if (this.aiText) {
					if (this.selectedVoice) {
						this.submitLoading = true;
						await this.depot.post(api.aiCard("aiVideo/createVideo"),{
							voiceType: this.selectedVoice,
							text: this.aiText,
							imgUrl: this.imgUrl,
							cropFaceTaskId: this.cropFaceTaskId,
							aiFigureId: this.aiFigureId
						})
						this.submitLoading = false;
						
						if (this.cardInfo) {
							uni.reLaunch({
								url: "/pages/aiPerson/createAiPersonSuccess"
							})
						} else {
							uni.reLaunch({
								url: "/pages/card/edit?fromCreateAiPerson=true"
							})
						}
					} else {
						this.$refs.toast.show({
							type: "error",
							title: "提示",
							message: "请选择声音"
						});
					}
				} else {
					this.$refs.toast.show({
						type: "error",
						title: "提示",
						message: "请输入智能体自我介绍的内容"
					});
				}
			}
		}
	};
</script>

<style lang="less" scoped>
	.createAiPersonStepTwo {
		min-height: 100vh;
		padding: 20rpx;
		position: relative;
		&-btnBlank {
			height: calc(100rpx - env(safe-area-inset-bottom));
		}
		&-btnList {
			width: 100vw;
			position: absolute;
			bottom: env(safe-area-inset-bottom);
			&-btn {
				width: 95vw;
			}
		}
	}
	
	.voiceList {
		width: 80vw;
	}
</style>
